<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Admin extends CI_Controller {

    function __construct(){
        parent::__construct();
        $this->load->model('product/product_model');
        #$this->load->model('admin/admin_model');
        $this->load->library('upload');
        $this->load->library('image_lib');

        if (!isset($_SESSION['admin']) && ($this->router->method != 'login')){
            redirect('admin/login');
        }
    }

    public function index(){
        /* $data['product_newest'] = $this->product_model->get_product(0, 0, 6, 0, 'create_date', 'DESC');
        $data['product_hot'] = $this->product_model->get_product_hot(0, 6); */
        $data['tpl'] = 'admin/index';
        $this->load->view('_layout/admin', $data);
    }

    function order(){
        $data['tpl'] = 'admin/index';
        $this->load->view('_layout/admin', $data);
    }

    function active(){
        $_id_key       = $this->input->post('id_key');
        $_id_value     = $this->input->post('id_value');
        $_field_key    = $this->input->post('field_key');
        $_field_value  = $this->input->post('field_value');
        $_table        = $this->input->post('table');
        $_field_value  = ($_field_value == 1) ? 0 : 1;
        $this->db->where($_id_key, $_id_value)->update($_table, array($_field_key => $_field_value));
        die(true);
    }

    function upload(){
        try {
            $upload_type = html_escape($this->input->get('type'));
            $upload_id   = $this->input->get('id');
            $mode        = $this->input->get('mode');
            $result      = array();

            //Check upload data
            if (empty($upload_type) || empty($upload_id)){
                die(json_encode(array('status' => false, 'msg' => 'param is missing')));
            }

            //Load library for upload, image
            include_once APPPATH.'libraries/fileuploader.php';
            $this->load->library('image_lib');

            //Create & get path uploader dir
            $upload_path = dirname($_SERVER['SCRIPT_FILENAME']).'/uploads/'.$upload_type.'/'.$upload_id.'/';

            if (!is_dir($upload_path)) {
                @mkdir($upload_path, 0755, true);
            }

            //Check writeable
            if (!is_writable($upload_path)){
                die(htmlspecialchars(json_encode(array('success' => false, 'msg' => 'ThÆ° má»¥c lÆ°u áº£nh khÃ´ng thá»ƒ ghi. Vui lÃ²ng thá»­ láº¡i !')), ENT_NOQUOTES));
            }

            // list of valid extensions, ex. array("jpeg", "xml", "bmp")
            $allowedExtensions = array('jpeg', 'jpg', 'png', 'bmp', 'gif');

            // max file size in bytes
            $sizeLimit = 2 * 1024 * 1024;

            //Create a instance uploader
            $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);

            //Upload file
            $result = $uploader->handleUpload($upload_path);

            if (isset($result['error'])) {
                die(htmlspecialchars(json_encode(array('success' => false, 'msg' => $result['error'])), ENT_NOQUOTES));
            }

            //File uploaded name
            $file_uploaded = $upload_path.$result['filename'];

            if ($mode == 'simple'){
                $max_width  = 500;
                $max_height = 500;
                $filename = trim($this->input->get('filename'));

                //Rename file after upload
                $filename_new = $filename != '' ? $filename : md5($upload_id).'.jpg';
                if (file_exists($upload_path.$filename_new)){
                    @fclose($upload_path.$filename_new);
                    @unlink($upload_path.$filename_new);
                }
                @rename($upload_path.$result['filename'], $upload_path.$filename_new);

                //Resize
                #setMemoryForImage($upload_path.$filename_new);
                $config = array(
                    'source_image'       => $upload_path.$filename_new,
                    'maintain_ratio'     => true
                );
                $dataimage               = getimagesize($upload_path.$filename_new);
                if (($dataimage[0] > $max_width) || ($dataimage[1] > $max_height)) {
                    $config['width']     = $max_width;
                    $config['height']    = $max_height;
                }
                $this->image_lib->initialize($config);
                $this->image_lib->resize();

                $result['type']     = $upload_type;
                $result['id']       = $upload_id;
                $result['mode']     = $mode;
                $result['id']       = $upload_id;
                $result['type']     = $upload_type;
                $result['image']    = $filename_new;
                $result['url']      = 'uploads/'.$upload_type.'/'.$upload_id.'/'.$filename_new.'?t='.time();
                $result['path']     = $upload_path;
            } else {
                $upload_id   = !empty($upload_id) ? $upload_id : random_string('alpha',6);

                $max_width  = 1024;
                $max_height = 1024;

                //Rename file after upload
                $filename_new = random_string('unique').'.'.strtolower($result['ext']);
                @fclose($upload_path.$result['filename']);
                if (file_exists($upload_path.$filename_new)) {
                    $filename_new = random_string('unique').'.'.strtolower($result['ext']);
                }
                @rename($upload_path.$result['filename'], $upload_path.$filename_new);

                //Resize
                #setMemoryForImage($upload_path.$filename_new);
                $config = array(
                    'source_image'       => $upload_path.$filename_new,
                    'maintain_ratio'     => true
                );
                $dataimage               = getimagesize($upload_path.$filename_new);
                if (($dataimage[0] > $max_width) || ($dataimage[1] > $max_height)) {
                    $config['width']     = $max_width;
                    $config['height']    = $max_height;
                }
                $this->image_lib->initialize($config);
                $this->image_lib->resize();

                //Update database
                $gallery = array(
                    'product_id'         => $upload_id,
                    'image'              => $filename_new,
                    'update_date'        => date('Y-m-d H:i:s', time()),
                    'create_date'        => date('Y-m-d H:i:s', time()),
                );
                $this->db->insert(TBL_GALLERY, $gallery);

                //Update info response for client
                $result['gallery_id']    = $this->db->insert_id();
                $result['id']            = $upload_id;
                $result['type']          = $upload_type;
                $result['image']         = $filename_new;
                $result['path']          = 'uploads/'.$upload_type.'/'.$upload_id.'/'.$filename_new.'?t='.time();;
                $result['resize']        = $dataimage;
                #$result['file_upload']  = $file_uploaded;
            }
            echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
        } catch (Exception $e){
            _debug($e);
        }
    }

    function upload2(){
        $max_width = 1024;
        $max_height = 1024;
        include_once APPPATH.'libraries/fileuploader.php';
        $type = $this->input->get('type');
        $id = $this->input->get('id');
        $mode = $this->input->get('mode') == 'simple' ? true : false;

        $allowedExtensions = array('jpeg', 'jpg', 'png', 'gif');
        //$sizeLimit = 4 * 1024 * 1024;

        $uploader = new qqFileUploader($allowedExtensions);

        //Create & get path uploader dir
        $upload_path = $_SERVER['DOCUMENT_ROOT'].'/uploads/'.$type.'/'.$id.'/';
        if (!is_dir($upload_path)) {
            @mkdir($upload_path, 0755, true);
        }

        //Upload file
        $result = $uploader->handleUpload($upload_path);
        $file_uploaded = $upload_path.@$result['filename'];
        if (isset($result['error'])){
            $return['status'] = false;
            $return['msg']    = $result['error'];
        } else {
            //Rename file after upload
            $newname = random_string('unique').'.'.strtolower($result['ext']);
            @fclose($upload_path.$result['filename']);
            @rename($upload_path.$result['filename'], $upload_path.$newname);

            //Resize images
            #setMemoryForImage($upload_path.$newname);
            $config = array(
                    'source_image'    => $upload_path.$newname,
                    'maintain_ratio'  => true
            );
            $dataimage                = @getimagesize($upload_path.$newname);
            if (($dataimage[0] > $max_width) || ($dataimage[1] > $max_height)) {
                $config['width']    = $max_width;
                $config['height']    = $max_height;
            }
            $this->image_lib->initialize($config);
            $this->image_lib->resize();

            //Update database
            $gallery_info = array(
                'product_id'     => $id,
                'image'          => $newname,
                'create_date'    => date('Y-m-d H:i:s', time()),
                'update_date'    => date('Y-m-d H:i:s', time())
            );
            $this->db->insert('gallery', $gallery_info);

            //Update info response for client
            $return['status'] = true;
            $return['filename'] = 'uploads/'.$type.'/'.$id.'/'.$newname;
            $return['id']       = $this->db->insert_id();
        }

        // to pass data through iframe you will need to encode all html tags
        die(htmlspecialchars(json_encode($return), ENT_NOQUOTES));
    }

    function logout(){
        unset($_SESSION['admin']);
        redirect('admin/login');
    }

    function login(){
        if (isset($_SESSION['admin']['id'])){
            redirect('admin/index');
        }

        if ($_POST){
            $username = $this->input->post('username');
            $password = $this->input->post('password');
            $exist = $this->db
                          ->select('*')
                          ->from(TBL_USER)
                          ->where('username', $username)
                          ->where('password', sha1($password))->get()->row_array();

            if (isset($exist['id'])){
                $_SESSION['admin'] = $exist;
                redirect('admin/index');
            } else {
                $data['msg'] = 'Tên đăng nhập hoặc mật khẩu không chính xác !';
            }
        }

        $data['tpl'] = 'admin/login';
        $this->load->view('_layout/single', $data);
    }

    function remove_image(){
        $gallery_id = intval($this->input->post('gallery_id'));
        $result = $this->product_model->remove_image($gallery_id);
        echo $result;
    }
}